const { CleanWebpackPlugin } = require('clean-webpack-plugin') // 这里需要把CleanWebpackPlugin写在{}里
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')

const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}
module.exports = {
  mode: 'production', // 模式
  entry: './src/main.ts', // 入口
  output: {
    // 出口
    path: resolve('dist-web'), // 打包文件
    filename: '[contenthash].bundle.js', // 每个输出 bundle 的名称
    chunkFilename: (pathData) => {
      // 未被列在入口的代码
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js'
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader',
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              appendTsSuffixTo: [/\.vue$/]
            }
          }
        ]
      },
      {
        test: /\.(css|scss)$/,
        use: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        test: /\.(svg|otf|ttf|woff2?|eot|gif|png|jpe?g)(\?\S*)?$/,
        loader: 'url-loader',
        // todo: 这种写法有待调整
        options: {
          limit: 10000,
          name: path.posix.join('static', '[name].[hash:7].[ext]')
        }
      }
    ]
  },
  // 配置模块如何解析
  resolve: {
    // 需要解析的文件后缀名
    extensions: ['.ts', '.tsx', '.js', '.vue'],
    // 别名配置
    alias: {
      '/@': resolve('src')
    }
  },
  plugins: [
    // 删除之前的打包文件
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: ['./dist-web']
    }),
    // 模板
    new HtmlWebpackPlugin({
      template: './src/assets/index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      }
    }),
    new VueLoaderPlugin()
  ]
}
